<?php

namespace services\patient;

use common\models\hospital\Expense;
use services\common\ExcelService;
use Yii;
use common\components\Service;
use common\models\patient\ConsumptionDetail;

/**
 * Class ConsumptionDetailService
 * @package services\patient
 */
class ConsumptionDetailService extends Service
{
    /**
     * 根据ID查找信息
     *
     * @param int $id
     * @return ConsumptionDetail|null
     */
    public function findById(int $id = 0): ?ConsumptionDetail
    {
        return ConsumptionDetail::find()->where(['id' => $id])->one();
    }

    /**
     * 查找信息
     *
     * @param array $condition
     * @return ConsumptionDetail|null
     */
    public function findInfo(array $condition = []): ?ConsumptionDetail
    {
        $query = ConsumptionDetail::find();

//        isset($condition['patient_user_id']) && $query->andWhere(['patient_user_id' => $condition['patient_user_id']]);
//        isset($condition['body_parts_id']) && $query->andWhere(['body_parts_id' => $condition['body_parts_id']]);

        return $query->one();
    }

    /**
     * 查找列表
     *
     * @param array $condition
     * @return array|\yii\db\ActiveRecord[]
     */
    public function findList(array $condition = [])
    {
        $query = ConsumptionDetail::find();

        isset($condition['status']) && $query->andWhere(['status' => $condition['status']]);

        return $query->asArray()->all();
    }

    /**
     * 患者消费信息列表
     *
     * @param array $params
     * @param int $page
     * @param int $pageSize
     * @return array
     */
    public function getListPage(array $params = [], int $page = 0, int $pageSize = 0)
    {
        $query = ConsumptionDetail::find()->select(['*'])
            ->where([
                'consumption_id' => $params['consumption_id'],
            ]);

        $query->orderBy(['created_at' => SORT_ASC, 'id' => SORT_ASC]);

        // 总数
        $total = $query->count();

        // 分页
        if ($page && $pageSize) {
            $query->limit($pageSize)->offset(($page - 1) * $pageSize);
        }

        $list = $query->asArray()->all();

        return [
            'page' => (int)$page,
            'pageSize' => (int)$pageSize,
            'total' => (int)$total,
            'list' => $list,
        ];
    }

    /**
     * 格式化列表数据
     *
     * @param array $data
     * @param int $type
     * @return array
     */
    public function getListPageFormat(array $data)
    {
        $list = [];
        foreach ($data as $row) {
            $item = [
                'id' => $row['id'],
                'consumption_id' => $row['consumption_id'],
                'patient_card_id' => $row['patient_card_id'],
                'drug_name' => $row['drug_name'],
                'drug_num' => $row['drug_num'],
                'drug_unit' => $row['drug_unit'],
                'drug_type' => $row['drug_type'],
                'price' => $row['price'],
                'money' => $row['money'],
                'discount_rate' => $row['discount_rate'],
                'reality_money' => $row['reality_money'],
                'consumption_type' => $row['consumption_type'],
                'consumption_type_str' => ConsumptionDetail::$consupmtionTypes[$row['consumption_type']],
            ];

            $list[] = $item;
        }

        return $list;
    }

    /**
     * 修复消费数据【删除重复记录】
     * @param int $projectId
     * @return void
     * @throws \Throwable
     * @throws \yii\db\StaleObjectException
     */
    public function repairConsumptionDetail(int $projectId)
    {
        $name_sx = ExcelService::getRedisProject($projectId);
        Expense::$pix = $name_sx;

        // 重复亦远消费ID【tb_ChargeDetail_Clinic】
        $repeatData = Expense::find()
            ->select(['type', 'serial_no', 'count(*) cnt'])
            ->where(['>', 'serial_no', 0])
            ->having(['>', 'cnt', 1])
            ->groupBy('type, serial_no')
            ->asArray()
            ->all();
        $repartId = [];
        foreach ($repeatData as $row) {
            /**
             * @var Expense[] $expenseList
             */
            $expenseList = Expense::find()
                ->where(['in', 'serial_no', $row['serial_no']])
                ->andWhere(['type' => $row['type']])
                ->all();
            foreach ($expenseList as $expense) {
                if (!in_array($expense->serial_no, $repartId)) {
                    $repartId[] = $expense->serial_no;
                    continue;
                }
                $expense->delete();

                ConsumptionDetail::deleteAll([
                    'yiyuan_aid' => $expense->id
                ]);

                echo "删除serial_no：{$expense->serial_no}, expense_id：{$expense->id}".PHP_EOL;
            }
        }
    }
}
